package cn.yiueil.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;

@Slf4j
@Aspect
@Component
public class TimeAdvice {
    @Around(value = "@annotation(cn.yiueil.annotation.Time)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) {
        LocalDateTime startDateTime = LocalDateTime.now();
        Object proceed = null;
        try {
            proceed = proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        LocalDateTime endDateTime = LocalDateTime.now();
        Duration duration = Duration.between(startDateTime, endDateTime);
        Signature signature = proceedingJoinPoint.getSignature();
        if (signature instanceof MethodSignature) {
            log.debug("方法" + ((MethodSignature) signature).getMethod().getName() + "()调用耗时" + duration.toMillis() + "毫秒");
        } else {
            log.debug("未知方法调用耗时" + duration.toMillis() + "毫秒");
        }
        return proceed;
    }
}
